const { User } = require("../model");
const jwt = require("../util/jwt");
const { jwtSecret } = require("../config/config.default");

// 处理注册逻辑中间件
module.exports.register = async (req, res, next) => {
  try {
    // 1. 数据验证
    // 2. 保存数据到数据库
    let user = new User(req.body.user);
    await user.save();
    // 3. 发送响应
    res.status(200).json({ user });
  } catch (err) {
    next(err);
  }
};

// 处理登录逻辑中间件
module.exports.login = async (req, res, next) => {
  try {
    // 1. 数据验证
    // 2. 生成jsonwebtoken
    let user = req.user;
    const token = await jwt.sign(
      {
        userId: user._id,
      },
      jwtSecret,
      {
        expiresIn: 60 * 60 * 24,
      }
    );
    user = JSON.parse(JSON.stringify(user));
    delete user.password;
    console.log(user);
    // 3. 发送响应
    res.status(200).json({
      token,
      user,
    });
  } catch (err) {
    next(err);
  }
};

// 处理查询用户的逻辑中间件
module.exports.getUser = async (req, res, next) => {
  try {
    const username = req.params.name;
    const user = await User.findOne({ username });
    user = JSON.parse(JSON.stringify(user));
    delete user.email;
    res.status(200).json({
      user,
    });
  } catch (err) {
    next(err);
  }
};
